
package models

import (
	"errors"
)

type SystemUser struct {
	Id            int       `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	Username          string    `json:"username" xorm:"not null comment('用户名') VARCHAR(50)"`
	Password      string    `json:"password" xorm:"not null comment('密码') index VARCHAR(50)"`
	Realname      string    `json:"realname" xorm:"not null default '' comment('真实姓名') unique VARCHAR(50)"`
	Salt          string    `json:"salt" xorm:"not null comment('盐') VARCHAR(4)"`
	Telphone         string    `json:"telphone" xorm:"not null default '' comment('手机号') VARCHAR(11)"`
	Comment  string    `json:"comment" xorm:"not null default '' comment('简介') VARCHAR(300)"`

}

type SearchUser struct  {
	Username string `json:"username" xorm:"not null comment('姓名') VARCHAR(50)"`
}

type UserSessionInfo struct {
	UserId int
	Username string
	RoleIds []int  //这个用户的权限，一个用户可能有多个权限
}

var systemuser = "system_user"

func(u *SystemUser) GetRow() bool {
	has, err := mEngine.Get(u)
	if err==nil &&  has  {
		return true
	}
	return false
}
func (u *SystemUser) GetAll()([]SystemUser,error) {
	var systemusers []SystemUser
	err:=mEngine.Find(&systemusers)
	return systemusers,err
}

func (u *SystemUser) GetById() (SystemUser,error) {
	var systemusers []SystemUser
	var emptyUser SystemUser
	err:=mEngine.Table(systemuser).Where("Id = ?",u.Id).Find(&systemusers )
	if len(systemusers)==0{
		return emptyUser, errors.New("no user name ")
	}

	return systemusers[0],err
}


func (u *SystemUser) GetAllByName(username string)([]SearchUser,error) {
	var systemusers []SearchUser

	err:=mEngine.Table(systemuser).Where("username like ?",username+"%").Find(&systemusers)
	return systemusers,err
}



func (u *SystemUser) Add(roleid int) (int ,error){
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return 0,err
	}
	//var uid int64
	_,err:=session.Insert(u)
	if err!=nil {
		return 0,err
	}
	//如果没有设置权限


	roleModel:=SystemRole{}
	roleModel.Id=roleid
	has:=roleModel.GetRow()
	if has {
		//如果角色存在
		userroleModel:=SystemUserRole{RoleId:roleModel.Id,UserId:u.Id}
		//查询数据库中该用户角色的数据是否已经有了。 session通过放射来操作数据库，如何放射的，还不太清楚
		has,err:=session.Get(&userroleModel)
		if err!=nil {
			return 0,err
		}
		//如果用户角色不存在，添加用户角色
		if !has {
			_,err=session.Insert(&userroleModel)
			if err!=nil {
				return 0,err
			}
		}


	}



	return u.Id,session.Commit()
}
func (u *SystemUser) Update(roles []interface{}) error {
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	if _, err := mEngine.Where("id = ?", u.Id).Update(u); err != nil {
		return err
	}
	roleModel:=SystemUserRole{}
	if _, err := mEngine.Where("userid=?",u.Id).Delete(&roleModel); err != nil {
		return err
	}
	//如果没有设置权限
	if len(roles)<1 {
		return session.Commit()
	}
	for _,k:=range roles{
		roleModel:=SystemRole{Rolename:k.(string)}
		has:=roleModel.GetRow()
		if !has {
			continue
		}

		userroleModel:=SystemUserRole{RoleId:roleModel.Id,UserId:u.Id}
		has,err:=session.Get(&userroleModel)
		if err!=nil {
			return err
		}
		if has {
			continue
		}
		_,err=session.Insert(&userroleModel)
		if err!=nil {
			return err
		}
	}
	return session.Commit()
}
func (u *SystemUser) UpdatePasswd() error {
	if _, err := mEngine.Where("id = ?", u.Id).Update(u); err != nil {
		return err
	}
	return nil
}

func (u *SystemUser) Delete() error {
	if _, err := mEngine.Exec("delete "+systemuser+"  where id=?",u.Id); err != nil {
		return err
	}
	return nil
}
